package net.yla.smartbus.core.util;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.util.TablesNamesFinder;
import org.springframework.stereotype.Repository;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : yanglei
 * @Date : Created in 18:21 2020/8/19
 * @description :
 */
@Repository
@Slf4j
public class SqlTableUtil {

    private static CCJSqlParserManager sqlParserManager = new CCJSqlParserManager();
    private static TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();

    /**
     * detect table names from given table
     * ATTENTION : WE WILL SKIP SCALAR SUBQUERY IN PROJECTION CLAUSE
     */
    public static List<String> getTableNames(String sql) throws Exception {
        Statement statement = sqlParserManager.parse(new StringReader(sql));
        Statement state = null;
        if (statement instanceof Select) {
            state = (Select) statement;
            return tablesNamesFinder.getTableList((Select) state);
        } else if (statement instanceof Insert) {
            state = (Insert) statement;
            return tablesNamesFinder.getTableList((Insert) state);
        } else if (statement instanceof Update) {
            state = (Update) statement;
            return tablesNamesFinder.getTableList((Update) state);
        } else {
            state = (Delete) statement;
            return tablesNamesFinder.getTableList((Delete) state);
        }
    }
}
